package com.lagou.edu.factory;

import com.lagou.edu.annotation.Autowired;
import com.lagou.edu.annotation.Service;
import com.lagou.edu.utils.TransactionManager;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.sql.SQLException;

/**
 * @author zyy
 * @date 2020/11/22 2:14 下午
 * @description
 */
@Service
public class ProxyFactory {
    @Autowired
    private TransactionManager transactionManager;
    public void setTransactionManager(TransactionManager transactionManager) {
        this.transactionManager = transactionManager;
    }

    /**
     * Jdk动态代理
     * @param target
     * @return
     */
    public Object getJdkProxy(Object target){
        return Proxy.newProxyInstance(ProxyFactory.class.getClassLoader(), target.getClass().getInterfaces(), new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                Object result = null;
                try {
                    //开启事务
                    transactionManager.beginTransaction();
                    //调用原来的业务逻辑
                    result = method.invoke(target, args);
                    //提交事务
                    transactionManager.commit();
                } catch (Exception throwables) {
                    throwables.printStackTrace();
                    //事务回滚
                    transactionManager.rollback();

                    //事务上抛 便于servlet
                    throw throwables;
                }
                return result;
            }
        });
    }

    /**
     * Cglib 动态代理生成代理对象
     * @param object
     * @return
     */
    public Object getCglibProxy(Object object){
        return Enhancer.create(object.getClass(), new MethodInterceptor() {
            @Override
            public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
                Object result;
                try {
                    // 开启事务(关闭事务的自动提交)
                    transactionManager.beginTransaction();
                    //调用原来的业务逻辑
                    result = method.invoke(object, objects);
                    //提交事务
                    transactionManager.commit();

                }catch (Exception e){
                    e.printStackTrace();
                    //事务回滚
                    transactionManager.rollback();
                    //事务上抛 便于servlet处理
                    throw e;
                }
                return result;
            }
        });
    }
}
